<?php

namespace api\modules\mini\forms;

use common\models\api\AccessToken;
use common\models\user\User;

/**
 * Class LoginForm
 * @package api\modules\v1\forms
 *
 */
class LoginForm extends \common\models\member\LoginForm
{
    public $group;
    public $openid;

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['openid', 'group'], 'required'],
//            ['openid', 'validateOpenid'],
            ['group', 'in', 'range' => AccessToken::getKeys()]
        ];
    }

    public function attributeLabels()
    {
        return [
            'openid' => '微信openid',
            'group' => '组别',
        ];
    }

    /**
     * 验证openid
     *
     * @param $attribute
     */
    public function validateOpenid($attribute)
    {
        if (!$this->hasErrors()) {
            /* @var $user \common\models\base\BaseUser */
            $user = $this->getUser();
            if (!$user) {
                $this->addError($attribute, '用户不存在');
            }
        }
    }


    /**
     * 用户登录
     *
     * @return mixed|null|static
     */
    public function getUser()
    {
        if ($this->_user == false) {
            // email 登录
            $this->_user = User::findOne(['wx_mini_openid' => $this->openid]);
        }

        return $this->_user;
    }
}
